<?php 
$_tos_configs = array();
function tos_add_config($k, $v) {
    global $_tos_configs;
    if (isset($_tos_configs[$k])) {
        tos_die("Config $k has already been set.");
    } else {
        if (empty($v)) {
            tos_die("Config value for $k cannot be empty");
        }
        $_tos_configs[$k] = $v;
    }
}
function tos_set_config($k, $v) {
    global $_tos_configs;
    
    if (empty($v)) {
        tos_die("Config value for $k cannot be empty");
    }
    $_tos_configs[$k] = $v;
    
}
function tos_get_config($k) {
    global $_tos_configs;
    if ( ! isset($_tos_configs[$k])) {
        return false;
    } else {
        return $_tos_configs[$k];
    }
}


$_tos_dbs = array(); 
function tos_add_db($name, $options) {
    global $_tos_dbs;
    
    $name = trim($name);
    if (empty($name)) {
        tos_die("db adapter name cannot be empty");
    }
    
    if ( ! isset($_tos_dbs[$name])) {
        $_tos_dbs[$name] = new Db_mysqli($options);
    } else {
        tos_die("db adapter $name already exists");
    }
    
    return true;
}
function tos_get_db($name = 'default') {
    global $_tos_dbs;
    
    $name = trim($name);
    if (empty($name)) {
        $name = 'default';
    }
    if (isset($_tos_dbs[$name])) {
        return $_tos_dbs[$name];
    } else {
        return false;
    }
}


function m($module_name) {
    static $ms = array();
    
    $module_name = trim($module_name);
    if (empty($module_name)) {
        tos_die('module name cannot be none');
    }
    
    if ( ! isset($ms[$module_name])) {
        
        /*
        $is_sys = false;
        if (defined('SITE_DIR')) {
            $dir = SITE_DIR . "/module/$module_name";
            $file = "$dir/$module_name.php";
            if ( ! file_exists($file)) {
                $is_sys = true;
            }
        } else {
            $is_sys = true;
        }*/
        $is_sys = true;
        if ($is_sys) {
            $dir = SYS_MODULE_DIR . "/$module_name";
            $file = "$dir/$module_name.php";
            if ( ! file_exists($file)) {
                tos_die("cannot find module [$module_name] file");
            }
        }
        
        
        include $file;
        
        $class_name = ucfirst($module_name);
        
        if ( ! class_exists($class_name)) {
            tos_die("$class_name doesn't exists.");
        }
        
        $obj = new $class_name();
        $obj->set_name($module_name);
        $obj->set_dir($dir);
        $obj->init();
        
        $ms[$module_name] = $obj;
    }
    
    return $ms[$module_name];
}


function out() {
    static $out;
    if ( ! isset($out)) {
        $out = new View_out('out');
    }
    return $out;
}


function tos_cdn_url($uri, $cdn_path = '', $cdn = array()) {
    $uri = trim($uri);
    $cdn_path = trim($cdn_path);
    $cdn = (array) $cdn;
    
    $cdn_path = empty($cdn_path) ? tos_get_config('cdn_path') : $cdn_path;
    $cdn = $cdn ? $cdn : tos_get_config('cdn');
    
    return "http://{$cdn['url']}/{$cdn_path}/{$uri}";
}


function tos_http_post($key) {
    return isset($_POST[$key]) ? trim($_POST[$key]) : '';
}

function tos_http_get($key) {
    return isset($_GET[$key]) ? trim($_GET[$key]) : '';
}

function tos_clean_url_segment($str) {
    $str = strtolower($str); 
    //$str = preg_replace('/\s+\+\s+/', ' ', $str); 
    $str = preg_replace('/[^a-z0-9]+/i', '-', $str); // leave letters and numbers (separated by space) only 
    $str = trim($str, '-'); 
    //$str = preg_replace('/\s+/i', '-', $str); 
    return $str; 
    //return urlencode($str); 

}

function tos_explode_keywords($str, $delimiter = ',') {
    $str = strtolower($str);
    $delimiter = (string) $delimiter;
    //$delimiter = trim($delimiter);
    
    if (empty($delimiter)) {
        $delimiter = ',';
    }
    if ($delimiter === '_') {
        $delimiter = ',';
    }
    if ($delimiter === ' ') {
        $preg = '/[^a-z0-9_ ]/i';//delimiter 
    } else {
        $preg = '/[^a-z0-9_ ' . $delimiter . ']/i';
    }
    //echo $preg;
    $str = preg_replace($preg, '', $str);
    $str = trim($str, $delimiter);
    return explode($delimiter, $str);
}

function tos_html_strip($html, $length = 500) {
    $str = preg_replace('/<[^><]*>/i', '', $html);
    $str = preg_replace('/\s+/i', ' ', $str);
    $length = (int) $length;
    if ($length) {
        $pos = strpos($str, ' ', $length);
        if ($pos)
            $str = substr($str, 0, $pos) . '......';
    }
    return $str;
}

function tos_redirect($ps, $is_new = false) {

    $str = tos_link($ps, $is_new);
    //return '?' . $str;
    header("Location: $str");
    exit();
}

function tos_link($ps, $is_new = false) {
    
    $arr = array();
    if ( ! $is_new) {
        $ps = array_merge($_GET, $ps);
    }
    foreach ($ps as $k => $v) {
        $k = trim($k);
        $v = trim($v);
        if ( ! empty($k) && ! empty($v)) {
            $arr[] = "$k=$v";
        }
    }
    $str = "?" . implode('&', $arr);
    
    return $str;
}

function tos_img($src, $alt = '', $width = 0, $height = 0, $attributes = array()) {
    $cdn = tos_get_config('cdn');
    $cdn_dir = $cdn['dir'];
    $cdn_url = $cdn['url'];
    
    $src = trim($src);
    if (empty($src)) {
        return '';
    }
    
    $img_src = 'http://' . $cdn_url . '/' . $src;
    
    $str = '';
    if ($attributes) {
        $arr = array();
        foreach ($attributes as $k => $v) {
            $str  .= " $k=\"$v\"";
        }
        //$str = ' ' . implode(' ', $arr);
    }
    if ($width === 0 && $height === 0) {
        return "<img src=\"{$img_src}\" alt=\"{$alt}\"{$str}/>";
    } else {
        $img_path = $cdn_dir . '/' . $src;
        $pathinfo = pathinfo($src);
        if ($width === 0 || $height === 0) {
            $size = getimagesize($img_path);
            //print_r($size);
            if ($width === 0) {
                $width = ceil($height * $size[0] / $size[1]);
            } else if ($height === 0) {
                $height = ceil($width * $size[1] / $size[0]);
            }
        }
        $new_src = $pathinfo['dirname'] . '/' . $pathinfo['filename'] . 
                "-{$width}x{$height}.{$pathinfo['extension']}";
        $new_img_path = $cdn_dir . '/' . $new_src;
        if ( ! file_exists($new_img_path)) {
            _resize_image($new_img_path, $img_path, $width, $height);
        } 
        
        $new_img_src = 'http://' . $cdn_url . '/' . $new_src;
        return "<img src=\"{$new_img_src}\" width=\"$width\" height=\"$height\" alt=\"{$alt}\"{$str}/>"; 
    }
}

function _resize_image($dest, $resc, $width, $height) {
    $im_dest = imagecreatetruecolor($width, $height);
    $im_resc;
    
    $ext = strtolower(pathinfo($resc, PATHINFO_EXTENSION));
    if ($ext === 'png') {
        $im_resc = imagecreatefrompng($resc);
    } else if ($ext === 'jpg') {
        $im_resc = imagecreatefromjpeg($resc);
    }
    if ( ! $im_resc) {
        tos_die('resize img failed');
    }
    
    list($resc_width, $resc_height) = getimagesize($resc);
    
    
    imagecopyresampled($im_dest, $im_resc, 0, 0, 0, 0, $width, $height, $resc_width, $resc_height);
    imagedestroy($im_resc);
    
    if ($ext === 'png') {
        imagepng($im_dest, $dest);
    } else if ($ext === 'jpg') {
        imagejpeg($im_dest, $dest);
    }
    
    imagedestroy($im_dest);
}

function tos_die($message = '') {
    echo $message;
    debug_print_backtrace();
    die();
}




?>